package com.devgroupvn.guinness.youtube;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

import com.devgroupvn.guinness.R;

public class YoutubeView extends RelativeLayout implements OnClickListener, DialogInterface.OnClickListener
{
	HttpURLConnection _connection;
	boolean _connecting;
	Context _context;
	String _id;
	ImageView _thumbImage;
	YoutubeData _youtubeData;
	private ImageView _playImage;
	YoutubeView _self;
	SoftReference<Bitmap> _bitmap;
	private Date _today;

	public YoutubeView(Context context)
	{
		super(context);
		_thumbImage = new ImageView(context);
		setPlayImage(new ImageView(context));
		_thumbImage.setScaleType(ScaleType.FIT_XY);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ico_audiodefault);
		bitmap = Util.createShadow(bitmap, 0);
		_thumbImage.setImageBitmap(bitmap);
		getPlayImage().setImageResource(R.drawable.f001_play);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
		getPlayImage().setLayoutParams(layoutParams);
		this._context = context;
		this.addView(_thumbImage, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		_self = this;
		_connecting = false;
		this.setClickable(true);
		this.setOnClickListener(this);
		// _today = DownloadAndCacheImage.getNowDate();
	}

	public YoutubeView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		_thumbImage = new ImageView(context);
		setPlayImage(new ImageView(context));
		_thumbImage.setScaleType(ScaleType.FIT_XY);
		_thumbImage.setImageResource(R.drawable.ico_audiodefault);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
		getPlayImage().setLayoutParams(layoutParams);
		getPlayImage().setImageResource(R.drawable.f001_play);
		this._context = context;
		this.addView(_thumbImage, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		_self = this;
		_connecting = false;
		this.setClickable(true);
		this.setOnClickListener(this);
		// _today = DownloadAndCacheImage.getNowDate();
	}

	public boolean isConnecting()
	{
		return _connecting;
	}

	private void cleanUp()
	{
		if (_connection != null)
		{
			try
			{
				_connection.disconnect();
			}
			catch (Exception ex)
			{
			}
			_connection = null;
		}
		_connecting = false;
	}

	protected void finalize() throws Throwable
	{
		if (_connecting)
			cleanUp();
		super.finalize();
	}

	public void getImage(YoutubeData youtubeData)
	{
		this._youtubeData = youtubeData;
		if (_bitmap != null && _bitmap.get() != null)
		{
			_thumbImage.setImageBitmap(_bitmap.get());
			return;
		}

		_id = Util.hashString(youtubeData.getMediaId());

		String cacheDir = _context.getCacheDir().toString();
		String dir = cacheDir + "/" + _id;
		// String dirDay2=cacheDir + "/"+
		// DownloadAndCacheImage.getDayString(DownloadAndCacheImage.getDateBefore(_today,1))+"/"
		// + _id + "_ytb.png";
		// String dirDay1=cacheDir + "/"+
		// DownloadAndCacheImage.getDayString(DownloadAndCacheImage.getDateBefore(_today,2))+"/"
		// + _id + "_ytb.png";

		File file = new File(dir);
		// File fileDay1 = new File(dirDay1);
		// File fileDay2 = new File(dirDay2);

		//
		// if (fileDay1.exists())
		// {
		// fileDay1.renameTo(file);
		// fileDay1.delete();
		// } else if (fileDay2.exists())
		// {
		// fileDay2.renameTo(file);
		// fileDay2.delete();
		// }
		if (file.exists())
		{
			// BitmapFactory.Options options = new BitmapFactory.Options();
			// options.inTempStorage = new byte[16 * 1024];
			// options.inSampleSize = 4;
			Bitmap bitmap = BitmapFactory.decodeFile(dir);
			bitmap = Util.createShadow(bitmap, 0);
			_bitmap = new SoftReference<Bitmap>(bitmap);
			_thumbImage.setImageBitmap(_bitmap.get());
			if (getPlayImage().getParent() == null)
				_self.addView(getPlayImage());
		}
		else
		{
			if (_connecting)
				return;
			else
			{
				_connecting = true;
				new DownloadTask().execute(new String[]
				{ youtubeData.getThumbnailLink(), "" });
			}
		}
	}

	public class DownloadTask extends AsyncTask<String, Void, Bitmap>
	{
		// SEND REQUEST
		@Override
		protected Bitmap doInBackground(String... urls)
		{
			// TODO Auto-generated method stub
			try
			{
				URL url = new URL(urls[0]);
				_connection = (HttpURLConnection) url.openConnection();
				_connection.setRequestMethod("GET");
				_connection.setDoInput(true);
				_connection.setDoOutput(true);
				int httpCode = _connection.getResponseCode();
				if (httpCode == HttpURLConnection.HTTP_OK)
				{
					InputStream in = new BufferedInputStream(_connection.getInputStream());
					return BitmapFactory.decodeStream(in);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				cleanUp();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap buff)
		{
			super.onPostExecute(buff);
			if (buff != null)
			{
				String fileName = "";
				try
				{
					String parent = _context.getCacheDir() + "";
					fileName = parent + "/" + _id;

					FileOutputStream out = new FileOutputStream(fileName);
					buff.compress(Bitmap.CompressFormat.PNG, 100, out);
					out.flush();
					out.close();

					buff = Util.createShadow(buff, 0);

					_bitmap = new SoftReference<Bitmap>(buff);
					_thumbImage.setImageBitmap(_bitmap.get());
					if (getPlayImage().getParent() == null)
						_self.addView(getPlayImage());
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					File fileSaved = new File(fileName);
					if (fileSaved.exists())
						cleanUp();
				}

			}
		}
	}

	private boolean[] _listSelected;

	@Override
	public void onClick(View v)
	{
		// TODO Auto-generated method stub
		if (_youtubeData.getVideoLink() != null)
		{
			gotoYoutube();
		}
	}

	public void setPlayImage(ImageView playImage)
	{
		this._playImage = playImage;
	}

	public ImageView getPlayImage()
	{
		return _playImage;
	}

	@Override
	public void onClick(DialogInterface dialog, int which)
	{
		gotoYoutube();
	}

	private void gotoYoutube()
	{
		String link = null;
		if (_youtubeData.getVideoLink().contains("http"))
			link = _youtubeData.getVideoLink();
		else if (_youtubeData.getMediaId().contains("http"))
			link = _youtubeData.getMediaId();
		if (link != null)
		{
			_context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
		}
	}
}
